<template>
  <div class="">
    <div class="center">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="礼包名称" prop="packName">
          <el-input
            maxlength="16"
            v-model.trim="queryParams.packName"
            placeholder="请输入礼包名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" fit-input-width clearable placeholder="请选择">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="进行中" value="1"></el-option>
            <el-option label="已失效" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="城市标签" prop="cityName">
          <el-select
            v-model="queryParams.cityName"
            @change="handleQuery"
            fit-input-width
            placeholder="请选择"
          >
            <el-option
              v-for="item in cityNameOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            icon="Plus"
            type="primary"
            @click="handleAdd"
            v-hasPermi="['marketing:giftPack:add']"
          >
            新建
          </el-button>
        </el-col>

        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" size="default" index :data="dataList">
        <el-table-column
          label="礼包名称"
          min-width="150px"
          align="center"
          prop="packName"
          show-overflow-tooltip
        />
        <el-table-column label="城市标签" align="center" prop="cityName" show-overflow-tooltip />
        <el-table-column label="礼包内容" align="center">
          <template #default="{ row }">
            <!-- TODO:礼包内容展示赠券数总数 -->
            <el-link
              :underline="false"
              :disabled="!hasPermi(['marketing:giftPack:content'])"
              type="primary"
              @click="handleGiftContent(row.id)"
              >{{ row.couponCount }}张</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="已领取" align="center">
          <template #default="{ row }">
            <el-link
              :disabled="!hasPermi(['marketing:giftPack:already'])"
              :underline="false"
              type="primary"
              @click="handlealReceived(row.id)"
              >{{ row.receiveCount }}</el-link
            >
          </template>
        </el-table-column>
        <el-table-column label="剩余" align="center" prop="surplusCount" />
        <el-table-column label="状态" width="100px" align="center" prop="status">
          <!-- [1:进行中,2:已失效] -->
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'warning'">{{
              row.status === 1 ? '进行中' : '已失效'
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right">
          <template #default="{ row }">
            <div style="display: flex; align-items: center; justify-content: center">
              <el-dropdown trigger="click" style="margin-right: 6px">
                <el-link
                  :underline="false"
                  type="primary"
                  v-hasPermi="['marketing:giftPack:extension']"
                  >推广</el-link
                >
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="getCouponLink(row)"
                      ><span>分享口令</span>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-link
                v-hasPermi="['marketing:giftPack:copy']"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleCopy(row)"
                >复制</el-link
              >
              <el-link
                v-hasPermi="['marketing:giftPack:delete']"
                v-if="row.status === 2"
                style="margin-right: 6px"
                :underline="false"
                type="danger"
                @click="handleDelete(row)"
                >删除</el-link
              >
              <el-link
                v-hasPermi="['marketing:giftPack:expire']"
                v-if="row.status !== 2"
                style="margin-right: 6px"
                :underline="false"
                type="primary"
                @click="handleExpire(row)"
                >失效</el-link
              >
              <el-link
                v-hasPermi="['marketing:giftPack:detail']"
                :underline="false"
                type="primary"
                @click="handleDetail(row)"
                >详情</el-link
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-right: 10px">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <addDialog ref="addRef" :title="title" @refresh="getList" />
    <detailDialog ref="detailRef" :title="title" />
    <giftContent ref="giftContentRef" />
    <alreadyReceived ref="alreadyReceivedRef" />
  </div>
</template>

<script setup>
import addDialog from './cpts/addDialog.vue'
import detailDialog from './cpts/detailDialog.vue'
import giftContent from './cpts/giftContent.vue'
import alreadyReceived from './cpts/alreadyReceived.vue'
import { getCouponPackListApi, updateCouponPackStatusApi } from '@/api/marketing/giftPack'
import { getCouponLinkApi } from '@/api/marketing/activity'
import useGlobalStore from '@/store/modules/global'
import { hasPermi } from '@/utils/tools'

const globalStore = useGlobalStore()
const cityNameOptions = computed(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  return globalStore.myCityList
})

const title = ref('')
const queryRef = ref(null)
const showSearch = ref(true)
const route = useRoute()

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  packName: '',
  time: '',
  status: '',
  id: '',
  cityName: ''
})

onMounted(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
})
const total = ref(0)
const dataList = ref([])
const loading = ref(false)

function getList() {
  loading.value = false
  const params = {
    ...queryParams,
    startTime: queryParams.time?.length ? queryParams.time[0] : '',
    endTime: queryParams.time?.length ? queryParams.time[1] : ''
  }
  delete params.time
  getCouponPackListApi(params)
    .then((res) => {
      loading.value = false
      dataList.value = res?.data?.rows || []
      total.value = res?.data?.total || 0
    })
    .catch(() => {
      loading.value = false
      dataList.value = []
      total.value = 0
    })
}

// 搜索
function handleQuery() {
  queryParams.pageNum = 1
  getList()
}

// 重置
function resetQuery() {
  queryParams.id = ''
  queryRef.value.resetFields()
  // Object.keys(queryParams).forEach((key) => {
  //   queryParams[key] = null
  // })
  // queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  // queryParams.status = ''
  handleQuery()
}

// 新建
const addRef = ref(null)
function handleAdd() {
  title.value = '优惠券礼包设置'
  addRef.value.init(queryParams.cityName)
}

// 礼包内容
const giftContentRef = ref(null)
function handleGiftContent(id) {
  giftContentRef.value.init(id, queryParams.cityName)
}

// 已领取
const alreadyReceivedRef = ref(null)
function handlealReceived(id) {
  alreadyReceivedRef.value.init(id)
}

/** 推广 */
const directionalRef = ref(null)
// 复制口令
function getCouponLink(row) {
  getCouponLinkApi({ marketingId: row.marketingId }).then((res) => {
    navigator.clipboard.writeText(res?.data).then(() => {
      ElMessage({
        message: '复制口令成功',
        type: 'success'
      })
    })
  })
}

// 复制
function handleCopy(row) {
  title.value = '优惠券礼包设置'
  addRef.value.init(row.cityName, row.id, true)
}

// 失效2 删除0
function handleDelete(row) {
  ElMessageBox.confirm('优惠券礼包记录将会被删除', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      updateCouponPackStatusApi({ id: row.id, status: 0 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        handleQuery()
      })
    })
    .catch(() => {})
}
function handleExpire(row) {
  ElMessageBox.confirm('优惠券礼包将会被强制失效', '操作', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'error'
  })
    .then(() => {
      updateCouponPackStatusApi({ id: row.id, status: 2 }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功'
        })
        getList()
      })
    })
    .catch(() => {})
}

// 详情
const detailRef = ref(null)
function handleDetail(row) {
  title.value = '优惠券礼包详情'
  addRef.value.init(row.cityName, row.id)
}

onMounted(() => {
  queryParams.cityName = globalStore.myCityList.length ? globalStore.myCityList[0] : ''
  console.log('onMounted', route.query)
  if (route.query.id) {
    queryParams.id = route.query.id
    queryParams.packName = route.query.packName
    queryParams.cityName = route.query.cityName
  }
  getList()
})
</script>

<style lang="scss" scoped>
.center {
  padding: 20px;
  .actions {
    align-items: center;
    display: flex;
  }
}
.name {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
